﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using JavaVirtualMachine;
using UnityEngine.UI;
using System.Threading;
using System.Configuration;
using System.Text.RegularExpressions;

public class StartScript : MonoBehaviour {
    public Text AppNameText;
    public static StartScript Ins;
    public Thread MainThread;
    Config Configuration;
    public bool IsUintyMainThreadRun;
    public bool OpenLog;
    public string RootPath = "C:\\Java";
    public string RtPath = "C:\\Java\\rt";
    public string[] AndroidFrameworkPath =new string[]{
    "C:\\Java\\AndroidGame\\sdk\\framework\\classes-dex2jar",
    "C:\\Java\\AndroidGame\\sdk\\framework\\classes2-dex2jar" };
    public string AppName="Mrps";
    public int TestValue = 1644230;
    public string EnResourcePath="";
    [HideInInspector]
    public string AppPath;
    [HideInInspector]
    public string AppDirectoryPath;
    [HideInInspector]
    public string ResourcePath;
    private void Awake()
    {
        Ins = this;
    }
    // Use this for initialization
    public void StartGame () {
       
        try
        {
            ResourcePath = RootPath + @"\";
            AppDirectoryPath = ResourcePath + AppName;
            AppPath = AppDirectoryPath + ".jar";
            Console.OpenLog = OpenLog;

            for (int i = 0; i < AndroidFrameworkPath.Length; i++)
            {
                AndroidFrameworkPath[i] += "\\";
            }

            if(!Directory.Exists(AppDirectoryPath))
            {
                Directory.CreateDirectory(AppDirectoryPath);
            }
            if (IsUintyMainThreadRun)
            {
                Run();
            }
            else
            {
                MainThread = new Thread(Run);
                MainThread.Start();
            }

            AppNameText.text = AppPath;
            GameGraphics.Ins.Show();
        }
        catch (IOException e)
        {
            Debug.LogError( e.Message);
            return;
        }
    }

    internal void OnClickEvent(bool v1, Vector2 normalizedPoint, bool v2)
    {
        Console.WriteLine("OnClickEvent");
    }

    public bool HasChinese(string str)
    {
        return Regex.IsMatch(str, @"[\u4e00-\u9fa5]");
    }

    void Run()
    {
        Configuration.srcPaths = new string[] { AppPath };
        Configuration.javaHome = RtPath;
        Configuration.androidPath = AndroidFrameworkPath;
        Configuration.rtPath = RtPath+"\\";
        Program.Configuration = Configuration;
        Program.Main(new string[] { Application.streamingAssetsPath + @"\config.json" });
    }

    // Update is called once per frame
    void Update () {
        //if(Input.GetKeyDown(KeyCode.G))
        // {
        //     MainThread = new Thread(Program.StartApp);
        //     MainThread.Start();
        // }
    }

    public static void MyStartCoroutine(IEnumerator enumerator)
    {
        Ins.StartCoroutine(enumerator);
    }

    IEnumerator Action()
    {
        yield return new MyWaitForSeconds(1);
    }

    private void OnApplicationQuit()
    {
        MainThread?.Abort();
        for (int i = 0; i < Program.threads.Count; i++)
        {
            Program.threads[i]?.Abort();
        }
        FileStreams.Dispose();
        JarFile.DisposeArchive();
        Console.Dispose();
    }

    //private void OnAudioFilterRead(float[] data, int channels)
    //{

    //}

    public AudioSource audioSource;//音频播放源

    /// <summary>
    /// 将byte[]转换成AudioClip
    /// </summary>
    /// <param name="data"></param>
    public void BytesToAudioClip(byte[] data)
    {
        float[] _clipData = bytesToFloat(data);//进行数据转换。将byte转成AudioClip可读取的float
        //audioSource.clip = AudioClip.Create("audioClip", 16000 * 10, 1, 16000, false);//不进行这一步，audioSource.clip会报空！
        audioSource.clip = AudioClip.Create("audioClip", _clipData.Length, 1,48000, false);//不进行这一步，audioSource.clip会报空！
        audioSource.clip.SetData(_clipData, 0);//完成赋值
        audioSource.Play();
    }
    public static float[] bytesToFloat(byte[] byteArray)//byte[]数组转化为AudioClip可读取的float[]类型
    {
        float[] sounddata = new float[byteArray.Length / 2];
        for (int i = 0; i < sounddata.Length; i++)
        {
            sounddata[i] = bytesToFloat(byteArray[i * 2], byteArray[i * 2 + 1]);
        }
        return sounddata;
    }
    static float bytesToFloat(byte firstByte, byte secondByte)
    {
        //小端和大端顺序要调整
        short s;
        float rescaleFactor = 32767;
        if (BitConverter.IsLittleEndian)
            s = (short)((secondByte << 8) | firstByte);
        else
            s = (short)((firstByte << 8) | secondByte);
        return s / 32768.0F;
    }
}

public class MyWaitForSeconds : MethodInfo
{
    public float time;

    public MyWaitForSeconds(float time)
    {
        this.time = time/1000f;
    }
}
